package cn.wit.summit.chwan.ui.base;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.event.BaseEvent;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.net.okhttplib.NetConfigStr;
import cn.wit.summit.chwan.ui.activity.DailyRecommendationActivity;
import cn.wit.summit.chwan.ui.activity.LoginV2Activity;
import cn.wit.summit.chwan.ui.activity.MainActivity;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.SystemBarTintManager;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadV2View;
import cn.wit.summit.chwan.widgets.RecommendTopWalletV2View;
import io.supercharge.shimmerlayout.ShimmerLayout;

/**
 * Created by tangbingliang on 17/2/16.
 */

public class BaseActivity extends PermissionBaseActivity {

    //region ACTION_BAR_NORMAL
    private   ImageView      barTitleIv;
    private   FrameLayout    rootContentNullLl;
    protected TextView       barTitleTx;
    private   RelativeLayout barTitleRl;
    private   ImageView      barBackIv;
    protected LinearLayout   barBackLl;
    private   TextView       barRightTx;
    protected ImageView      barRightIv;
    private   RelativeLayout barRightRl;
    protected RelativeLayout rootBarRl;
    private   LinearLayout   baseTopLl;
    //endregion

    //region ACTION_BAR_ENERGY_DOWNLOAD
    //    protected TextView                 barTitleTx;
    protected ImageView                back;
    protected RecommendTopWalletV2View recommendTopWallet;
    protected RecommendTopDownloadV2View recommendTopDownload;
    //endregion

    //region ROOT
    public  LinearLayout topLayout;
    private ImageView    barHeightIv;
    private FrameLayout  rootContentLl;
    private ImageView    baseLineIv;
    //endregion

    protected final int ACTION_BAR_CUSTOM          = 0;
    protected final int ACTION_BAR_NORMAL          = 1;
    protected final int ACTION_BAR_ENERGY_DOWNLOAD = 2;
    protected int actionBarStyle             = ACTION_BAR_ENERGY_DOWNLOAD;

    private ViewStub normal;
    private ViewStub energy_download;

    @Subscribe
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (actionBarStyle != ACTION_BAR_CUSTOM)
            super.setContentView(R.layout.activity_base);

        if (barHeightIv == null)
            barHeightIv = (ImageView) findViewById(R.id.barHeightIv);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(false);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

//            if (mAty instanceof DailyRecommendationActivity) {
//                if (barHeightIv != null)
//                    barHeightIv.setVisibility(View.GONE);
//            } else {
//                if (barHeightIv != null) {
//                    barHeightIv.setVisibility(View.VISIBLE);
//                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStateBarHeight());
//                    barHeightIv.setLayoutParams(params);
//                }
//                tintManager.setStatusBarTintResource(R.drawable.header_gradient_bg);// 通知栏所需颜色
//            }
        }
        EventBus.getDefault().register(mContext);
    }

    private void setTranslucentStatus(boolean on) {
        Window                     win       = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int                  bits      = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    public void setContentView(int layoutResID) {
        if (actionBarStyle == ACTION_BAR_CUSTOM) {
            super.setContentView(layoutResID);
            return;
        } else if (actionBarStyle == ACTION_BAR_NORMAL) {

            normal = (ViewStub) findViewById(R.id.normal);
            normal.inflate();

            //标题栏最外层
            rootBarRl = (RelativeLayout) findViewById(R.id.root_bar_rl);
            //标题栏标题外层
            barTitleRl = (RelativeLayout) findViewById(R.id.bar_title_rl);

            //标题栏标题文字控件
            barTitleTx = (TextView) findViewById(R.id.bar_title_tx);
            //标题栏标题图片控件
            barTitleIv = (ImageView) findViewById(R.id.bar_title_iv);

            //标题栏返回外层
            barBackLl = (LinearLayout) findViewById(R.id.bar_back_ll);
            barBackLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            //标题栏返回图片控件
            barBackIv = (ImageView) findViewById(R.id.bar_back_iv);

            //标题栏右边文字控件
            barRightTx = (TextView) findViewById(R.id.bar_right_tx);
            //标题栏右边图片控件
            barRightIv = (ImageView) findViewById(R.id.bar_right_iv);
            //标题栏右边外层
            barRightRl = (RelativeLayout) findViewById(R.id.bar_right_rl);
        } else if (actionBarStyle == ACTION_BAR_ENERGY_DOWNLOAD) {
            energy_download = (ViewStub) findViewById(R.id.energy_download);
            energy_download.inflate();

            //标题栏标题文字控件
            barTitleTx = (TextView) findViewById(R.id.bar_title_tx);
            back = findViewById(R.id.back);
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            recommendTopWallet = findViewById(R.id.recommendTopWallet);
            recommendTopDownload = findViewById(R.id.recommendTopDownload);

//            barHeightIv.setVisibility(View.VISIBLE);

            initEnergyDownloadView();
        }

        //基类内容显示区域
        rootContentLl = findViewById(R.id.root_content_ll);
        rootContentNullLl = (FrameLayout) findViewById(R.id.root_content_null_ll);
        rootContentNullLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new NotNetEvent(NetWorkUtils.isNetworkConnected(v.getContext())));
                if (NetWorkUtils.isNetworkConnected(v.getContext()))
                    reGetData();
                else
                    showToast(NetConfigStr.STR_CheckNet);
            }
        });
        try {
            onEventMainThread(new NotNetEvent(NetWorkUtils.isNetworkConnected(this)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        topLayout = (LinearLayout) findViewById(R.id.base_top_ll);
        //标题栏分割点
        baseLineIv = (ImageView) findViewById(R.id.base_line_iv);

        //子类布局
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View           v        = inflater.inflate(layoutResID, null);
        v.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        rootContentLl.addView(v);
    }

    //region initEnergyDownloadView
    protected void initEnergyDownloadView() {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.recommendTopEnergy://能量入口
                        break;
                    case R.id.recommendTopDownload://下载管理
                        break;
                }
            }
        };
    }
    //endregion

    /********************** 基类生命周期方法***********************/

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (recommendTopDownload != null) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    recommendTopDownload.setTotalDownloadNum();
                }
            }, 200);
        }
        changeLoginStatus();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        cancelLoading();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(mContext);
        super.onDestroy();
    }

    /*********************基类Title控件操作***********************/

    public RelativeLayout getRootBarRl() {
        return rootBarRl;
    }

    public FrameLayout getRootContentLl() {
        return rootContentLl;
    }

    /**
     * 返回按钮
     */
    protected LinearLayout getBarBackLl() {
        return barBackLl;
    }

    /**
     * 影藏头部
     */
    protected void hideTitleBar() {
        if (rootBarRl != null) {
            rootBarRl.setVisibility(View.GONE);
            baseLineIv.setVisibility(View.GONE);
        }
    }

    /**
     * 显示头部
     */
    protected void showTitleBar() {
        if (rootBarRl != null) {
            rootBarRl.setVisibility(View.VISIBLE);
            baseLineIv.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示标题文字，隐藏bar图片
     */
    public TextView setBarTitleTx(String str) {
        barTitleTx.setVisibility(View.VISIBLE);
//        barTitleIv.setVisibility(View.GONE);
        barTitleTx.setText(str);
        return barTitleTx;
    }

    /**
     * 显示标题文字，隐藏bar图片
     */
    public TextView setBarTitleTx(int id) {
        barTitleTx.setVisibility(View.VISIBLE);
        if (barTitleIv!=null)
            barTitleIv.setVisibility(View.GONE);
        barTitleTx.setText(getResources().getString(id));
        return barTitleTx;
    }

    /**
     * 显示标题图片，隐藏标题文字
     */
    public ImageView setBarTitleIv(int id) {
        barTitleTx.setVisibility(View.GONE);
        if (barTitleIv!=null){
            barTitleIv.setVisibility(View.VISIBLE);
            barTitleIv.setImageResource(id);
        }
        return barTitleIv;
    }

    /**
     * 显示标题右边文字，隐藏标题右边图片
     */
    protected ImageView setBarRightIv() {
        if (barRightIv!=null) {
            barRightIv.setVisibility(View.VISIBLE);
            barRightTx.setVisibility(View.GONE);
        }
        return barRightIv;
    }

    /**
     * 显示标题右边文字，隐藏标题右边图片
     */
    protected ImageView setBarRightIv(int id) {
        if (barRightIv!=null) {
            barRightIv.setVisibility(View.VISIBLE);
            barRightTx.setVisibility(View.GONE);
            barRightIv.setImageResource(id);
        }
        return barRightIv;
    }

    /**
     * 显示标题右边
     */
    protected RelativeLayout getBarRightRl() {
        barRightRl.setVisibility(View.VISIBLE);
        return barRightRl;
    }

    /**
     * 显示标题右边图片，隐藏标题右边文字
     */
    protected TextView setBarRightTx(String txt) {
        if (barRightIv!=null) {
            barRightTx.setVisibility(View.VISIBLE);
            barRightIv.setVisibility(View.GONE);
            barRightTx.setText(txt);
        }
        return barRightTx;
    }

    /**
     * 显示标题右边图片，隐藏标题右边文字
     */
    protected TextView setBarRightTx(int id) {
        if (barRightIv!=null) {
            barRightTx.setVisibility(View.VISIBLE);
            barRightIv.setVisibility(View.GONE);
            barRightTx.setText(getResources().getString(id));
        }
        return barRightTx;
    }

    public ImageView getBarHeightIv() {
        return barHeightIv;
    }

    /********************** 基类帮助方法***********************/

    public void removeAll() {
        exitApp();
    }

    //在注册了的Activity中,声明处理事件的方法
    @Subscribe(threadMode = ThreadMode.MAIN) //第2步:注册一个在后台线程执行的方法,用于接收事件
    public void onUserEvent(BaseEvent baseEvent) {//参数必须是ClassEvent类型, 否则不会调用此方法
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && (mAty instanceof MainActivity
                || mAty instanceof LoginV2Activity)) {// 返回键
            exitBy2Click();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "One more exit program", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            exitApp();
            System.exit(0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (mAty instanceof MainActivity) return;
        if (isTopActivity()){
            if (notNetEvent.isHasNet) {
                rootContentLl.setVisibility(View.VISIBLE);
                rootContentNullLl.setVisibility(View.GONE);
            } else {
                rootContentLl.setVisibility(View.GONE);
                rootContentNullLl.setVisibility(View.VISIBLE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        if ( recommendTopDownload != null) {
            recommendTopDownload.setTotalDownloadNum();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EnergyEvent energyEvent) {
        if (recommendTopWallet != null) {
            recommendTopWallet.initTotalWalletNum();
        }
        showEnergyDialog(energyEvent.getNumber());
    }

    private void changeLoginStatus() {
        if (recommendTopWallet != null) {
            recommendTopWallet.initTotalWalletNum();
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMainThread(SensorChangedEvent sensorChangedEvent) {
//        if (recommendTopEnergy != null) {
//            recommendTopEnergy.changeRotate(sensorChangedEvent.degree);
//        }
//    }

    public void setTopBarDownload(RecommendTopDownloadV2View topBarDownload, RecommendTopWalletV2View topBarEnergy) {
        this.recommendTopDownload = topBarDownload;
        this.recommendTopWallet = topBarEnergy;
    }

    //region SkeletonScreen
    ShimmerLayout shimmerLayout;
    private int mShimmerColor;
    private boolean mShimmer         = true;
    private int     mShimmerDuration = 1200;
    private int     mShimmerAngle    = 20;
    View innerView;

    protected void initSkeleton() {
        if (!mShimmer) return;
        mShimmerColor = ContextCompat.getColor(this, R.color.shimmer_color);

        shimmerLayout = findViewById(R.id.shimmerLayout);
        shimmerLayout.setShimmerColor(mShimmerColor);
        shimmerLayout.setShimmerAngle(mShimmerAngle);
        shimmerLayout.setShimmerAnimationDuration(mShimmerDuration);

        innerView = LayoutInflater.from(this).inflate(getSkeletonLayoutId(), shimmerLayout, false);
        shimmerLayout.addView(innerView);
        shimmerLayout.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                shimmerLayout.startShimmerAnimation();
            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                shimmerLayout.stopShimmerAnimation();
            }
        });

    }

    protected int getSkeletonLayoutId() {
        return -1;
    }

    protected void showSkeleton() {
        if (innerView == null) initSkeleton();
        if (innerView == null) return;
        if (shimmerLayout == null) return;
        shimmerLayout.setVisibility(View.VISIBLE);
        shimmerLayout.startShimmerAnimation();
    }

    protected void hideSkeleton() {
        if (innerView == null) initSkeleton();
        if (innerView == null) return;
        if (shimmerLayout == null) return;
        shimmerLayout.setVisibility(View.GONE);
        shimmerLayout.stopShimmerAnimation();
    }
    //endregion
}
